<template>
  <div class="box">
    <!-- 头部搜索模块 -->
    <headerSearch :selectObj="selectObject" :isShowAdd="menuFlag" :goSearchFc="searchClick" :buttonList="buttonList" />
    <!-- 中间表格模块 -->
    <BaseTable :data="splitVotetableData" :columns="splitVoteDataColumns" @details="selectDataList"
      :tableHeight="tableHeight" :pagination="false" :loading="loading"></BaseTable>

    <div class="page">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryAll.startpage" :page-sizes="[10, 15, 20, 25, 30]" :page-size="queryAll.pagesize"
        layout="total, sizes, prev, pager, next, jumper" :total="queryAll.totalNum"></el-pagination>
    </div>
    <!-- 分票明细 -->
    <el-drawer :before-close="handleClose" :visible.sync="drawerInner" direction="rtl" size="85%">
      <template slot="title">
        <div>
          <div>分票明细</div>
          <div style="display: flex;float: right;margin-top: -20px;margin-right: 30px;">
            <el-button size="mini" type="primary" @click="addLotting">添加</el-button>
          </div>
        </div>
      </template>
      <el-form :model="lottingForm" ref="basisRulesRef" size="small">
        <el-table :data="lottingForm.lottingDetailedData" border :height="tableHeight + 100">
          <el-table-column label="分票号">
            <template slot-scope="scope">
              <el-form-item :prop="`lottingDetailedData[${scope.$index}].splitBillNo`"
                :rules="[{ required: true, message: '分票号不能为空' }]">
                <el-input v-model="scope.row.splitBillNo"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="票货" width="210">
            <template slot-scope="scope">
              <el-form-item :prop="`lottingDetailedData[${scope.$index}].cargoInfoId`"
                :rules="[{ required: true, message: '票货不能为空' }]">
                <el-select v-model="scope.row.cargoInfoId"
                  @change="changeValue('cargoInfoId', scope.$index, scope.row.cargoInfoId)">
                  <el-option v-for="item in DataListById" :key="item.cargoInfoId" :label="item.customerShortName"
                    :value="item.cargoInfoId"></el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="树种" width="120">
            <template slot-scope="scope">
              <el-form-item prop="treeSpeciesCode">
                <el-select v-model="scope.row.treeSpeciesCode"
                  @change="changeValue('treeSpeciesCode', scope.$index, scope.row.treeSpeciesCode)">
                  <el-option v-for="item in treeTypeList" :key="item.dictValue" :label="item.dictLabel"
                    :value="item.dictValue"></el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <!-- <el-table-column label="货主" width="200">
            <template slot-scope="scope">
              <el-form-item :prop="`lottingDetailedData[${scope.$index}].cargoOwnerId`"
                :rules="[{ required: true, message: '货主不能为空' }]">
                <el-select v-model="scope.row.cargoOwnerId"
                  @change="changeValue('cargoOwnerId', scope.$index, scope.row.cargoOwnerId)">
                  <el-option v-for="item in customerList" :key="item.cargoOwnerId" :label="item.cargoOwnerName"
                    :value="item.cargoOwnerId"></el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column> -->
          <!-- <el-table-column label="开证公司" width="200">
            <template slot-scope="scope">
              <el-form-item :prop="`lottingDetailedData[${scope.$index}].issuingCompanyId`"
                :rules="[{ required: true, message: '开证公司不能为空' }]">
                <el-select v-model="scope.row.issuingCompanyId"
                  @change="changeValue('issuingCompanyId', scope.$index, scope.row.issuingCompanyId)">
                  <el-option v-for="item in issuingCompanyList" :key="item.issuingCompanyId"
                    :label="item.issuingCompanyName" :value="item.issuingCompanyId"></el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column> -->
          <el-table-column label="lot">
            <template slot-scope="scope">
              <el-form-item prop="lot">
                <el-input v-model="scope.row.lot"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="材质">
            <template slot-scope="scope">
              <el-form-item :prop="`lottingDetailedData[${scope.$index}].material`"
                :rules="[{ required: true, message: '材质不能为空' }]">
                <el-input v-model="scope.row.material"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="规格">
            <template slot-scope="scope">
              <el-form-item :prop="`lottingDetailedData[${scope.$index}].specs`"
                :rules="[{ required: true, message: '规格不能为空' }]">
                <el-input v-model="scope.row.specs"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="舱号">
            <template slot-scope="scope">
              <el-form-item prop="cabin">
                <el-input v-model="scope.row.cabin"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="标记">
            <template slot-scope="scope">
              <el-form-item prop="mark">
                <el-input v-model="scope.row.mark" size="mini"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="件数">
            <template slot-scope="scope">
              <el-form-item :prop="`lottingDetailedData[${scope.$index}].quantity`"
                :rules="[{ required: true, message: '件数不能为空' }]">
                <el-input v-model="scope.row.quantity"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="体积">
            <template slot-scope="scope">
              <el-form-item :prop="`lottingDetailedData[${scope.$index}].volume`"
                :rules="[{ required: true, message: '体积不能为空' }]">
                <el-input v-model="scope.row.volume"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="场地" width="120">
            <template slot-scope="scope">
              <el-form-item :prop="scope.row.storehouseId">
                <el-select v-model="scope.row.storehouseId"
                  @change="changeValue('storehouseId', scope.$index, scope.row.storehouseId)">
                  <el-option v-for="item in yardList" :key="item.storehouseId" :label="item.storehouseName"
                    :value="item.storehouseId"></el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <!-- <el-table-column label="垛号" width="100">
            <template slot-scope="scope">
              <el-form-item prop="stackPosition">
                <el-input v-model="scope.row.stackPosition"></el-input>
              </el-form-item>
            </template>
          </el-table-column> -->
          <el-table-column label="操作" fixed="right" width="160">
            <template slot-scope="scope">
              <el-link type="primary" @click.native.prevent="copyCargoInfo(scope.$index, scope.row)">复制</el-link>
              <el-link type="primary" style="margin-left:10px;" :disabled="scope.row.id ? false : true"
                @click.native.prevent="drawerClick(scope.$index, lottingForm.lottingDetailedData)">绘制区域</el-link>
              <el-link type="danger" style="margin-left:10px;"
                @click.native.prevent="deleteCargoInfo(scope.$index, lottingForm.lottingDetailedData)">删除</el-link>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div class="demo-drawer__footer">
        <el-button type="primary" @click="submitInner()" :loading="ineerLoading" size="small">
          {{ ineerLoading ? "提交中 ..." : "保 存" }}
        </el-button>
        <el-button size="small" @click="drawerInner = false">取消</el-button>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import Utils from '@/libs/Utils.js'
import BaseTable from '@/components/BaseTable'
import dfilters from '@/libs/Utils.js'
import api from '@/api/yardTally/lottingManage'
import publicapi from '@/api/public'
import headerSearch from '@/components/headerSearch'
export default {
  components: {
    BaseTable,
    headerSearch
  },
  data() {
    return {
      menuFlag: false,
      oldOut: {},
      oldInner: {},
      ineerLoading: false,
      tableHeight: window.innerHeight - 200,
      // 搜索框显示对象
      selectObject: [
        {
          name: '船名航次',
          type: 'select',
          modelName: 'shipvoyageName',
          selectLabel: 'shipvoyageName',
          selectValue: 'shipvoyageName',
          selectData: []
        },
        {
          name: '选择状态',
          type: 'select',
          modelName: 'splitStatus',
          selectData: [
            {
              dictValue: '1',
              dictLabel: '未分票'
            }, {
              dictValue: '2',
              dictLabel: '已分票'
            }
          ],
          selectLabel: 'dictLabel',
          selectValue: 'dictValue'
        }
      ],
      // 按钮的list
      buttonList: [
        { label: '分票', icon: 'el-icon-price-tag', type: 'primary', click: () => this.addDrawerForm, permission: 'tallyManagement:lottingManage:lotting' }
      ],
      splitVoteDataColumns: [ // table表头
        { prop: 'shipvoyageName', label: '船名航次' },
        { prop: 'berthTime', label: '靠泊时间' },
        { prop: 'billNo', label: '提单号' },
        { prop: 'issuingCompanyName', label: '开证公司', isShort: true },
        { prop: 'customerName', label: '船代', isShort: true },
        { prop: 'cargoOwnerName', label: '货主', isShort: true },
        { prop: 'cargoCategoryName', label: '货种' },
        { prop: 'tradeType', label: '贸别' },
        {
          prop: 'splitStatus',
          label: '状态',
          render: (h, params) => {
            if (params.row.splitStatus == '1') {
              return h('el-tag', {
                props: {
                  size: 'mini',
                  type: 'danger'
                },
                domProps: {
                  innerHTML: '未分票'
                }
              })
            }
            return h('el-tag', {
              props: {
                size: 'mini',
                type: 'success'
              },
              domProps: {
                innerHTML: '已分票'
              }
            })
          }
        }
      ],
      splitVotetableData: [],
      shipVoyageData: [], // 船名航次数据
      yardList: [],
      treeTypeList: [],
      DataListById: [],
      loading: false,
      queryAll: {
        startpage: 1,
        pagesize: 10,
        totalNum: 0,
        shipvoyageName: '',
        settlementStatus: ''
      },
      detailsData: null,
      drawerOut: false,
      flagOut: true,
      outForm: {
        portName: '',
        portCode: '',
        logogram: '',
        nationCode: '',
        sortNum: ''
      },
      drawerInner: false,
      lottingForm: {
        lottingDetailedData: []
      }
    }
  },
  async activated() {
    this.getShipvoyage()
    this.getListTreeType()
    this.getListYard()
  },
  computed: {
  },
  methods: {
    /**
     * 获取船名航次
     */
    async getShipvoyage() {
      const res = await publicapi.getListShipvoyage()
      this.shipVoyageData = res.data.data
      this.selectObject[0].selectData = this.shipVoyageData
    },
    // 获取字典树种
    getListTreeType() {
      publicapi.getDictData('TREETYPE').then(res => {
        this.treeTypeList = res.data.data.TREETYPE
      })
    },
    // 获取库场信息
    getListYard() {
      publicapi.queryStorehouseNameByType('').then(res => {
        this.yardList = res.data.data
      })
    },
    // 获取数据
    async getData() {
      this.loading = true
      await api.getData(this.queryAll).then(res => {
        if (res.status == '200') {
          this.queryAll.startpage = res.data.data.pageNum
          this.queryAll.pagesize = res.data.data.pageSize
          this.queryAll.totalNum = res.data.data.totalNum
          this.splitVotetableData = res.data.data.pages
          this.splitVotetableData.forEach(item => {
            item.berthTime = dfilters.getProcessingDate(item.berthTime, '')
          })
          this.loading = false
        }
      })
    },
    /**
     * 分票
     */
    async addDrawerForm() {
      this.DataListById = []
      if (!this.detailsData) {
        return this.$message.warning('请选择一条数据')
      }
      if (!this.drawerInner) {
        this.drawerInner = true
      }
      const params = {
        id: this.detailsData.id,
        billId: this.detailsData.billId
      }
      await api.getDataById(params).then(res => {
        if (res.status == '200') {
          this.lottingForm.lottingDetailedData = res.data.data
          this.lottingForm.lottingDetailedData.forEach(item => {
            item.tradeType = this.detailsData.tradeType
            item.companyId = this.detailsData.companyId
            item.billId = this.detailsData.billId
            item.splitStatus = this.detailsData.splitStatus
          })
        }
      })
      const data = {
        id: this.detailsData.id,
        cargoInfoId: this.detailsData.cargoInfoId
      }
      // 根据id查询票货
      await api.getOneDataListById(data).then(res => {
        if (res.data.code == '0000') {
          this.DataListById = res.data.data
          console.log(this.DataListById);
        }
      })
    },
    // 选中数据
    selectDataList(val) {
      this.detailsData = null
      this.detailsData = val
      this.lottingForm.lottingDetailedData = []
      // 货种获取货名
      // publicapi.getListCargo({ cargoCategoryCode: this.detailsData.cargoCategoryCode }).then(res => {
      //   this.cargoList = res.data.data
      // })
    },
    // 删除
    deleteCargoInfo(index, rows) {
      this.$confirm('是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        rows.splice(index, 1);
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 复制
    copyCargoInfo(index, row) {
      // let data = {
      //   shipvoyageId: this.detailsData.id,
      //   billId: this.detailsData.billId,
      //   companyId: this.detailsData.companyId,
      //   shipName: this.detailsData.shipName,
      //   voyage: this.detailsData.voyage,
      //   splitBillNo: row.splitBillNo,
      //   cargoInfoId: row.cargoInfoId,
      //   treeSpeciesCode: row.treeSpeciesCode,
      //   treeSpeciesName: row.treeSpeciesName,
      //   cargoOwnerId: row.cargoOwnerId,
      //   cargoOwnerName: row.cargoOwnerName,
      //   cargoCode: row.cargoCode,
      //   cargoName: row.cargoName,
      //   issuingCompanyId: row.issuingCompanyId,
      //   issuingCompanyName: row.issuingCompanyName,
      //   tradeType: this.detailsData.tradeType,
      //   lot: row.lot,
      //   material: row.material,
      //   specs: row.specs,
      //   cabin: row.cabin,
      //   mark: row.mark,
      //   volume: row.volume,
      //   quantity: row.quantity,
      //   storehouseId: row.storehouseId,
      //   storehouseName: row.storehouseName,
      //   stackPosition: row.stackPosition,
      // }
      delete row.id
      const msg = JSON.parse(JSON.stringify(row))
      this.lottingForm.lottingDetailedData.push(msg)
    },
    /**
     * 新建、编辑保存
     */
    submitInner() {
      if (this.lottingForm.lottingDetailedData.length == 0) {
        return this.$message.error('至少包含一条数据')
      }
      const newArr = this.lottingForm.lottingDetailedData.map(item => item.splitBillNo)
      const arrSet = new Set(newArr)
      if (arrSet.size != newArr.length) {
        return this.$message.error('分票号不能重复')
      }
      this.$refs.basisRulesRef.validate((valid) => {
        if (valid) {
          api.updateData(this.lottingForm.lottingDetailedData).then(res => {
            if (res.data.code == '0000') {
              this.$message.success('保存成功')
              this.drawerInner = false
              this.getData()
            }
          })
        }
      })
    },
    searchClick(searchData) {
      this.queryAll.startpage = 1
      this.queryAll = Object.assign(this.queryAll, searchData)
      this.detailsData = null
      this.getData()
    },
    // 添加明细信息
    addLotting() {
      const data = {
        id: '',
        shipvoyageId: this.detailsData.id,
        billId: this.detailsData.billId,
        cargoInfoId: '',
        companyId: this.detailsData.companyId,
        shipName: this.detailsData.shipName,
        voyage: this.detailsData.voyage,
        splitBillNo: '',
        treeSpeciesCode: '',
        treeSpeciesName: '',
        // 货名
        cargoCode: '',
        cargoName: '',
        // 货主
        cargoOwnerId: '',
        cargoOwnerName: '',
        // 开证公司
        issuingCompanyId: '',
        issuingCompanyName: '',
        cargoAgentId: '',
        cargoAgentName: '',
        tradeType: this.detailsData.tradeType,
        lot: '',
        material: '',
        specs: '',
        cabin: '',
        mark: '',
        quantity: '',
        volume: '',
        storehouseId: '',
        storehouseName: '',
        stackPosition: '',
        splitStatus: this.detailsData.splitStatus
      }
      this.lottingForm.lottingDetailedData.push(data)
    },
    // 下拉框数据
    changeValue(msg, index, val) {
      if (msg == 'cargoInfoId') {
        const data = this.DataListById.filter(item => item.cargoInfoId == val)[0]
        this.lottingForm.lottingDetailedData[index].cargoCode = data.cargoCode
        this.lottingForm.lottingDetailedData[index].cargoName = data.cargoName
        this.lottingForm.lottingDetailedData[index].cargoOwnerId = data.cargoOwnerId
        this.lottingForm.lottingDetailedData[index].cargoOwnerName = data.cargoOwnerName
        this.lottingForm.lottingDetailedData[index].issuingCompanyId = data.issuingCompanyId
        this.lottingForm.lottingDetailedData[index].issuingCompanyName = data.issuingCompanyName
        this.lottingForm.lottingDetailedData[index].cargoAgentId = data.cargoAgentId
        this.lottingForm.lottingDetailedData[index].cargoAgentName = data.cargoAgentName
      } else if (msg == 'treeSpeciesCode') {
        this.lottingForm.lottingDetailedData[index].treeSpeciesName = this.treeTypeList.filter(item => item.dictValue == val)[0].dictLabel
      } else {
        this.lottingForm.lottingDetailedData[index].storehouseName = this.yardList.filter(item => item.storehouseId == val)[0].storehouseName
      }
    },
    async handleDelete(id) {
      this.$confirm('是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        api.reqDelete(id).then(res => {
          if (res.data.code === '0000') {
            this.getData()

            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleSizeChange(val) {
      this.queryAll.pagesize = val
      this.detailsData = null
      this.getData()
    },
    handleCurrentChange(val) {
      this.queryAll.startpage = val
      this.detailsData = null
      this.getData()
    },
    handleClose(done) {
      let oldV = {}
      let newV = {}
      if (this.drawerOut) {
        oldV = this.oldOut
        newV = this.outForm
      }
      if (this.drawerInner) {
        oldV = this.oldInner
        newV = this.innerForm
      }
      if (!Utils.compareData(oldV, newV)) {
        this.$confirm('修改的数据未保存，是否关闭？')
          .then(_ => {
            done()
          })
          .catch(_ => { })
      } else {
        done()
      }
    },
    // 路由跳转 -- 绘制区域
    drawerClick(index, val) {
      this.drawerInner = false
      this.$router.push(
        {
          name: 'shcoordinates',
          params: {
            cargoInfoId: val[0].cargoInfoId,
            storehouseId: val[0].storehouseId
          }
        }
      )
    }
  }
}
</script>

<style lang="less" scoped>
.selectBox {
  justify-content: space-between;
  display: flex;
  background: #ffffff;
  border: 1px solid #e1e4eb;
  border-bottom: 0;
  border-left: none;
  height: 50px;
  position: relative;
  align-items: center;
  padding-left: 14px;
  padding-right: 20px;
}

.input_box {
  display: flex;
}

.page {
  background: #ffffff;
  text-align: right;
  border-radius: 0 0 4px 4px;
  padding: 5px 20px;
}

/deep/.el-tabs--border-card>.el-tabs__content {
  padding: 0 !important;
}

//抽屉底部样式
/deep/ .el-drawer__header {
  margin-bottom: -10px;
  padding: 16px;
  border-bottom: 1px solid gainsboro;
}

.demo-drawer__footer {
  text-align: right;
  padding-right: 20px;
  border-top: 1px solid #c8cfde;
  background-color: #f5f7fa;
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  line-height: 50px;
}

.box {
  background: #ffffff;
  border: 1px solid #e1e4eb;
  border-radius: 4px 4px 0 0;
  border-top: none;
}

.el-form-item--small.el-form-item {
  margin-bottom: 0px;
}
</style>
